package com.ruoyi.system.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.github.pagehelper.PageInfo;
import com.ruoyi.common.core.page.PageDomain;
import com.ruoyi.common.core.page.TableSupport;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.constant.Constants;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.service.IScrTotalService;
import com.ruoyi.system.service.IUserInfoService;
import com.ruoyi.system.service.IUserInfoV2Service;
import com.ruoyi.system.utils.PageByList;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.service.IScrTotalV2Service;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 【请填写功能名称】Controller
 *
 * @author ruoyi
 * @date 2024-10-11
 */
@RestController
@RequestMapping("/system/totalv2")
public class ScrTotalV2Controller extends BaseController
{
    @Autowired
    private IScrTotalV2Service scrTotalV2Service;

    @Autowired
    private IUserInfoV2Service userInfoV2Service;



    @GetMapping("/list")
    public TableDataInfo list(ScrTotalV2 scrTotalV2)
    {
        String username = SecurityUtils.getUsername();
        String name = scrTotalV2.getName();
        scrTotalV2.setName("");
        HashMap<Long,Integer> idmap = new HashMap<>();
        idmap = scrTotalV2Service.selectScrTotalListbyuserv2(scrTotalV2,username);
        List<ScrTotalV2> scrTotalList = scrTotalV2Service.selectScrTotalV2List(scrTotalV2);
        List<ScrTotalV2> retList = new ArrayList<>();
        for(ScrTotalV2 scrTotalV21 : scrTotalList){
            if(idmap.containsKey(scrTotalV21.getScrId())){
                retList.add(scrTotalV21);
            }
        }
        scrTotalList.clear();
        for(ScrTotalV2 scrTotalV21:retList){
            scrTotalList.add(scrTotalV21);
        }

        List<ScrTotalV2> list1 = new ArrayList<>();
        for(ScrTotalV2 scrTotalV21 : scrTotalList){
            Long id = scrTotalV21.getUserInfoId();
            UserInfoV2 userInfoV2 = userInfoV2Service.selectUserInfoV2ById(id);
            scrTotalV21.setName(userInfoV2.getName());
            if(name == null || scrTotalV21.getName().contains(name)){
                list1.add(scrTotalV21);
            }
        }
        scrTotalList.clear();
        for(ScrTotalV2 scrTotalV21:list1){
            scrTotalList.add(scrTotalV21);
        }





        PageDomain pageDomain = TableSupport.buildPageRequest();
        Integer pageNum = pageDomain.getPageNum();
        Integer pageSize = pageDomain.getPageSize();
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(0);
        rspData.setRows(PageByList.startPage(scrTotalList, pageNum, pageSize));
        rspData.setTotal(new PageInfo(scrTotalList).getTotal());
        return rspData;

    }





    /**
     * 导出【请填写功能名称】列表
     */

    @PostMapping("/export")
    public void export(HttpServletResponse response, ScrTotalanduser scrTotalanduser)
    {
        List<ScrTotalanduser> list = scrTotalV2Service.selectScrTotalanduserListv2(scrTotalanduser);
        ExcelUtil<ScrTotalanduser> util = new ExcelUtil<ScrTotalanduser>(ScrTotalanduser.class);
        util.exportExcel(response, list, "电子量表数据");
    }


    @PostMapping("/export1")
    public void export1(HttpServletResponse response, ScrTotalanduser scrTotalanduser)
    {
        ScrTotalV2 scrTotalV2 = new ScrTotalV2();
        List<ScrTotalV2> list = scrTotalV2Service.selectScrTotalV2List(scrTotalV2);
        ExcelUtil<ScrTotalV2> util = new ExcelUtil<ScrTotalV2>(ScrTotalV2.class);
        util.exportExcel(response, list, "电子量表数据");
    }


    /**
     * 获取【请填写功能名称】详细信息
     */

    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(scrTotalV2Service.selectScrTotalV2ById(id));
    }


    @GetMapping(value = "/getuser{id}")
    public AjaxResult getuserInfo(@PathVariable("id") Long id) throws IOException {
        ScrTotalV2 scrTotalV2 = scrTotalV2Service.selectScrTotalV2ById(id);
        if(scrTotalV2.getUserInfoId()==-1){
            UserInfoV2 userInfoV2 = new UserInfoV2();
            userInfoV2.setName("未命名");
            userInfoV2Service.insertUserInfoV2(userInfoV2);
            scrTotalV2.setUserInfoId(userInfoV2.getId());
            scrTotalV2Service.updateScrTotalV2(scrTotalV2);
            return success(userInfoV2);
        }
        else {
            return success(userInfoV2Service.selectUserInfoV2ById(scrTotalV2.getUserInfoId()));
        }
    }

    @GetMapping(value = "/getscrid{id}")
    public AjaxResult getscrid(@PathVariable("id") Long id)
    {
        ScrTotalV2 scrTotalV2 = scrTotalV2Service.selectScrTotalV2ById(id);
        String url = "http://images.headdb.cn/"+"base_"+scrTotalV2.getScrId()+"_54402.png";//TODO:nginx要改
        //List<String>url = null;
        //url.add("D:\\nginx\\nginx-1.24.0\\nginx-1.24.0\\html\\"+"base_"+scrTotal.getScrId()+"_54257.png");
        //url.add("D:\\nginx\\nginx-1.24.0\\nginx-1.24.0\\html\\"+"base_"+scrTotal.getScrId()+"_54258.png");
        //url.add("D:\\nginx\\nginx-1.24.0\\nginx-1.24.0\\html\\"+"base_"+scrTotal.getScrId()+"_54259.png");
        return success(url);
    }


    /**
     * 新增【请填写功能名称】
     */

    @PostMapping
    public AjaxResult add(@RequestBody ScrTotalV2 scrTotalV2)
    {
        return toAjax(scrTotalV2Service.insertScrTotalV2(scrTotalV2));
    }

    /**
     * 修改【请填写功能名称】
     */

    @PutMapping
    public AjaxResult edit(@RequestBody ScrTotalV2 scrTotalV2)
    {
        System.out.println("ooooooooooooooooooooooooooooooooooooooo");
        System.out.println(scrTotalV2);
        try{
            return toAjax(scrTotalV2Service.updateScrTotalV2(scrTotalV2));

        }
        catch(Exception e){
            System.out.println(e);
            return AjaxResult.success();
        }
    }

    @PutMapping("/user")
    public AjaxResult edituser(@RequestBody UserInfoV2 userInfoV2)
    {
        return toAjax(userInfoV2Service.updateUserInfoV2(userInfoV2));
    }

    /**
     * 删除【请填写功能名称】
     */

    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(scrTotalV2Service.deleteScrTotalV2ByIds(ids));
    }

    @DeleteMapping("/id")
    public AjaxResult removesingle(@PathVariable Long id){
        return toAjax(scrTotalV2Service.deleteScrTotalV2ById(id));
    }



    @GetMapping("/download")
    public ResponseEntity<InputStreamResource> downloadFile(@RequestParam Integer id, @RequestParam String type) throws IOException {
        String dir="";
        String filename = id+"."+type;
        dir = Constants.BASE_DIR+id;
        Path filePath = Paths.get(dir,filename);
        File file = filePath.toFile();
        InputStreamResource resource = new InputStreamResource(new FileInputStream(file));
        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + filename);

        return ResponseEntity.ok()
                .headers(headers)
                .contentLength(file.length())
                .contentType(MediaType.parseMediaType("application/octet-stream"))
                .body(resource);
    }
}
